<template>
  <div class="learning-platform">
    <!-- 顶部导航栏 -->
    <AppHeader :user="user" />

    <main>
      <!-- 个人信息卡片 -->
      <div
        v-if="user"
        class="profile-section"
      >
        <div class="profile-card">
          <!-- 主信息区域 -->
          <div class="profile-main">
            <!-- 左侧头像和信息 -->
            <div class="profile-info">
              <img
                class="user-avatar"
                src="https://picsum.photos/120/120?random=user"
                alt="用户头像"
              >
              <div class="user-meta">
                <h2 class="username">
                  {{ user.userName }}
                </h2>
                <div class="account-info">
                  <span>账号：{{ user.userAccount }}</span>
                </div>
              </div>
            </div>

            <!-- 右侧操作按钮 -->
            <div class="profile-actions">
              <button
                class="settings-btn"
                @click="openAccountSettingsModal"
              >
                账号设置
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 账号设置模态框 -->
      <div
        v-if="showAccountSettingsModal"
        class="modal-backdrop"
      >
        <div class="modal-window">
          <div class="modal-header flex items-start">
            <!-- 文字内容容器 -->
            <div class="flex-1 pr-8 min-w-0">
              <h3 class="text-[clamp(1.25rem,2vw,1.5rem)] font-medium text-gray-800 mb-2">
                账号设置
              </h3>
              <p class="text-gray-600 text-sm break-words">
                {{ modalStep === 1 ? '请验证身份以修改账号' : '修改您的账号信息' }}
              </p>
            </div>

            <!-- 关闭按钮 -->
            <button
              class="close-btn shrink-0"
              @click="closeAccountSettingsModal"
            />
          </div>

          <div class="step-indicator mt-2">
            <div :class="['step', { active: modalStep === 1 }]" />
            <div :class="['step', { active: modalStep === 2 }]" />
          </div>

          <!-- 密码验证步骤 -->
          <div v-show="modalStep === 1">
            <div class="modal-body">
              <div class="form-group">
                <label for="account">账号</label>
                <input
                  id="account"
                  type="text"
                  class="form-input"
                  :value="user.userAccount"
                  readonly
                >
              </div>

              <div class="form-group">
                <label for="current-password">当前密码</label>
                <div class="password-toggle">
                  <input
                    id="current-password"
                    v-model="currentPassword"
                    type="password"
                    class="form-input"
                    placeholder="请输入当前密码"
                    autocomplete="current-password"
                  >
                  <button
                    class="toggle-password"
                    @click="togglePasswordVisibility('current-password')"
                  />
                </div>
                <p
                  v-if="passwordError"
                  class="error-message"
                >
                  {{ passwordError }}
                </p>
              </div>

              <div class="modal-footer">
                <button
                  class="btn btn-cancel"
                  @click="closeAccountSettingsModal"
                >
                  取消
                </button>
                <button
                  class="btn btn-confirm"
                  :disabled="currentPassword.trim() === '' || isVerifying"
                  @click="verifyPassword"
                >
                  {{ isVerifying ? '验证中...' : '验证' }}
                </button>
              </div>
            </div>
          </div>

          <!-- 账号设置步骤 -->
          <div v-show="modalStep === 2">
            <div class="modal-body">
              <div class="form-group">
                <label for="new-username">新用户名</label>
                <input
                  id="new-username"
                  v-model="newUsername"
                  type="text"
                  class="form-input"
                  placeholder="请输入新用户名"
                >
              </div>

              <div class="form-group">
                <label for="new-password">新密码</label>
                <div class="password-toggle">
                  <input
                    id="new-password"
                    v-model="newPassword"
                    type="password"
                    class="form-input"
                    placeholder="请输入新密码"
                  >
                  <button
                    class="toggle-password"
                    @click="togglePasswordVisibility('new-password')"
                  />
                </div>
              </div>

              <div class="form-group">
                <label for="confirm-password">确认新密码</label>
                <div class="password-toggle">
                  <input
                    id="confirm-password"
                    v-model="confirmPassword"
                    type="password"
                    class="form-input"
                    placeholder="请再次输入新密码"
                  >
                  <button
                    class="toggle-password"
                    @click="togglePasswordVisibility('confirm-password')"
                  />
                </div>
                <p
                  v-if="passwordMismatch"
                  class="error-message"
                >
                  两次输入的密码不一致
                </p>
              </div>

              <div class="modal-footer">
                <button
                  class="btn btn-cancel"
                  @click="closeAccountSettingsModal"
                >
                  取消
                </button>
                <button
                  class="btn btn-confirm"
                  :disabled="!newUsername || newUsername.trim() === '' || isSaving || passwordMismatch"
                  @click="saveAccountSettings"
                >
                  {{ isSaving ? '保存中...' : '保存更改' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 角色切换按钮 -->
      <div class="identity-switch">
        <button
          v-for="(label, index) in identityLabels"
          :key="index"
          :class="{ active: currentIdentity === identities[index] }"
          @click="switchIdentity(identities[index])"
        >
          {{ label }} <!-- 显示中文 -->
        </button>
      </div>

      <!-- 学习记录 -->
      <div
        v-show="currentIdentity === 'Student'"
        class="card-container"
      >
        <div class="study-header">
          <h3>课程进度</h3>
        </div>

        <div class="study-list">
          <!-- 动态渲染学习记录 -->
          <div
            v-if="isLoading"
            class="text-center py-4"
          >
            加载中...
          </div>
          <div
            v-for="record in studyRecords"
            :key="record.id"
            class="study-item"
          >
            <div class="thumbnail">
              <img
                :src="record.thumbnail"
                :alt="record.title + ' Thumbnail'"
              >
            </div>
            <div class="content">
              <div class="meta">
                <h4 class="title">
                  课程:
                  {{ record.title }}
                </h4>
                <span class="time">{{ record.time }}</span>
              </div>
              <p class="description">
                课程教学目标:
                {{ record.desc }}
              </p>
              <div class="progress-wrapper">
                <h4 class="progress-label">
                  学习进度
                </h4>
                <h4 class="progress-percentage text-uppercase">
                  {{ record.progress }}%
                </h4>
                <div
                  class="progress"
                  style="height: 10px;"
                >
                  <div
                    class="progress-bar bg-primary"
                    role="progressbar"
                    :aria-valuenow="record.progress"
                    aria-valuemin="0"
                    aria-valuemax="100"
                    :style="{ width: record.progress + '%' }"
                  />
                </div>
              </div>
            </div>

            <!-- 添加查看详情按钮 -->
            <button
              class="btn-view-detail"
              @click="viewLearningDetails(record.id)"
            >
              <span class="icon-wrapper">
                <i class="fas fa-list" />
              </span>
              <span class="btn-text">查看详情</span>
            </button>
          </div>

          <div class="study-list">
            <div
              v-if="isLoading"
              class="text-center py-4"
            >
              加载中...
            </div>
            <div
              v-for="record in studyRecords"
              :key="record.id"
              class="study-item"
            >
              <!-- 学习记录项 -->
            </div>
            <div
              v-if="studyRecords.length === 0"
              class="empty-study-record"
            >
              <i class="fa-solid fa-book-open" />
              <p>没有学习记录</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 班级管理 (教师身份) -->
      <div
        v-show="currentIdentity === 'Teacher' || currentIdentity === 'Teaching_Assistant'"
        class="card-container"
      >
        <div class="study-header">
          <h3>{{ currentIdentity === 'Teacher' ? '我教授的班级' : '我协助的班级' }}</h3>
        </div>

        <div class="class-list">
          <div
            v-if="isLoading"
            class="text-center py-4"
          >
            加载中...
          </div>

          <div
            v-else-if="classes.length === 0"
            class="empty-classes"
          >
            <i class="fa-solid fa-school" />
            <p>暂无班级信息</p>
          </div>

          <div v-else>
            <div
              v-for="classItem in classes"
              :key="classItem.classesId"
              :class="['study-item', { active: expandedClassId === classItem.classesId }]"
              @click="toggleExerciseList(classItem.classesId)"
            >
              <div class="thumbnail">
                <img
                  :src="classItem.course?.image || 'https://picsum.photos/100/100?random=course'"
                  :alt="classItem.course?.courseName + ' Thumbnail'"
                >
              </div>
              <div class="content">
                <div class="meta">
                  <h4 class="title">
                    {{ classItem.course?.courseName }}
                  </h4>
                  <span class="course-name">{{ classItem.classesName }}</span>
                </div>
                <p class="description">
                  {{ classItem.course?.course || '暂无课程描述' }}
                </p>
                <div class="progress-wrapper">
                  <h4 class="progress-label">
                    班级学生已完成课程比例
                  </h4>
                  <h4 class="progress-percentage text-uppercase">
                    {{ classItem.completionRate }}%
                  </h4>
                  <div
                    class="progress"
                    style="height: 10px;"
                  >
                    <div
                      class="progress-bar bg-primary"
                      role="progressbar"
                      :aria-valuenow="classItem.completionRate"
                      aria-valuemin="0"
                      aria-valuemax="100"
                      :style="{ width: `${classItem.completionRate}%` }"
                    />
                  </div>
                </div>
              </div>
              <i class="fas fa-chevron-down toggle-indicator" />
              <transition name="slide">
                <!-- 练习列表（展开时显示） -->
                <div
                  v-show="expandedClassId === classItem.classesId"
                  class="student-list"
                >
                  <table class="student-table">
                    <thead>
                      <tr>
                        <th scope="col">
                          练习名称
                        </th>
                        <th scope="col">
                          开始时间
                        </th>
                        <th scope="col">
                          截止时间
                        </th>
                        <th scope="col">
                          完成进度
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr
                        v-for="exercise in classItem.exercises"
                        :key="exercise.exerciseId"
                      >
                        <td>{{ exercise.exerciseName }}</td>
                        <td>{{ formatDate(exercise.exerciseStartTime) }}</td>
                        <td>{{ formatDate(exercise.exerciseDeadline) }}</td>
                        <td>{{ exercise.completionRate }}%</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </transition>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
  <FooterComponent />
</template>

<script>
import axios from 'axios';
import AppHeader from '@/components/main_page/AppHeader.vue';
import { useUserStore } from '@/stores/userStore'; // 引入 store

import FooterComponent from "@/components/UserCenter/FooterComponent.vue";


export default {
  name: 'UserCenter',
  components: {FooterComponent, AppHeader},
  setup() {
    const userStore = useUserStore(); // 使用 store
    return {
      userStore // 暴露给模板使用
    };
  },
  data() {
    return {
      user: null,
      stats: {
        publishedCourses: 0,
        learningCourses: 0,
        studentsCount: 0,
        completionRate: 0
      },
      studyRecords: [],
      courses: [],
      classes: [], // 班级列表
      isLoading: false,
      error: null,
      identities: ['Student', 'Teacher'],
      // 中文显示值
      identityLabels: ['学生', '教师或助教'],
      currentIdentity: 'Student',
      expandedClassId: null, // 当前展开的班级ID

      // 账号设置相关状态
      showAccountSettingsModal: false,
      modalStep: 1, // 1: 密码验证, 2: 账号设置
      currentPassword: '',
      newUsername: '',
      newPassword: '',
      confirmPassword: '',
      passwordError: '',
      isVerifying: false,
      isSaving: false
    }
  },
  computed: {
    passwordMismatch() {
      return this.newPassword && this.newPassword !== this.confirmPassword;
    }
  },
  async mounted() {
    const userStore = useUserStore();
    
    // 从store获取用户信息，并确保获取的是纯数据对象而非Proxy
    let storeUser = userStore.user;
    
    // 处理可能的Proxy对象
    if (storeUser && typeof storeUser === 'object') {
      // 检查是否为Proxy对象
      if (storeUser.data && storeUser.data.userId) {
        console.log('从Proxy对象中提取用户数据');
        this.user = { ...storeUser.data }; // 创建纯数据对象的副本
      } else if (storeUser.target && storeUser.target.data && storeUser.target.data.userId) {
        console.log('从Proxy对象的target中提取用户数据');
        this.user = { ...storeUser.target.data }; // 创建纯数据对象的副本
      } else if (storeUser.userId) {
        console.log('从store获取的用户数据格式正确');
        this.user = { ...storeUser }; // 创建纯数据对象的副本
      } else {
        console.log('无法从store获取有效的用户数据');
        this.user = null;
      }
    } else {
      console.log('store中的用户数据无效或不存在');
      this.user = null;
    }
    
    // 添加保护，确保用户数据存在
    if (!this.user || !this.user.userId) {
      console.error('用户数据未正确加载');
      // 检查localStorage中是否有token
      const token = localStorage.getItem('token');
      if (!token) {
        console.log('未找到有效的认证令牌，重定向到登录页面');
        this.$router.push('/login');
        return;
      } else {
        console.log('发现认证令牌，但用户数据不完整，尝试重新获取用户信息');
        try {
          // 尝试通过token重新获取用户信息
          const response = await axios.get('/api/users/current');
          if (response.status === 200 && response.data) {
            // 确保获取的是纯数据对象
            const userData = response.data.data || response.data;
            // 更新用户信息
            this.user = { ...userData };
            userStore.$patch({
              user: { ...userData }
            });
            console.log('成功恢复用户会话，用户数据:', this.user);
          } else {
            throw new Error('无法恢复用户会话');
          }
        } catch (error) {
          console.error('恢复用户会话失败，需要重新登录:', error);
          localStorage.removeItem('token'); // 清除可能已失效的token
          this.$router.push('/login');
          return;
        }
      }
    }
    
    console.log('当前组件的用户信息:', this.user);
    
    // 添加重试机制获取完整用户信息
    let retryCount = 0;
    const maxRetries = 2;
    
    // 确保有有效的userId
    if (!this.user || !this.user.userId) {
      console.error('无法获取有效的userId，无法继续获取用户详细信息');
      this.error = '用户信息加载失败，请重新登录';
      this.$router.push('/login');
      return;
    }
    
    while (retryCount <= maxRetries) {
      try {
        const response = await axios.get(`/api/users/${this.user.userId}`);
        
        if (response.status === 200) {
          // 确保获取的是纯数据对象
          const userData = response.data.data || response.data;
          
          if (userData && typeof userData === 'object') {
            // 设置完整的用户对象
            this.user = { ...userData };
            // 同时更新store中的用户信息
            userStore.$patch({
              user: { ...userData }
            });
            console.log('获取到的完整用户信息:', this.user);
            break; // 成功获取数据，跳出循环
          } else {
            throw new Error('获取的用户数据格式不正确');
          }
        } else {
          throw new Error(`获取用户信息失败: ${response.status}`);
        }
      } catch (error) {
        retryCount++;
        console.error(`获取用户信息出错 (尝试 ${retryCount}/${maxRetries}):`, error);
        
        if (error.response?.status === 401 || error.response?.status === 403) {
          console.log('用户未授权或会话已过期，重定向到登录页面');
          localStorage.removeItem('token');
          this.$router.push('/login');
          return;
        }
        
        if (retryCount > maxRetries) {
          console.error('达到最大重试次数，无法获取用户信息');
          this.error = '无法加载用户信息，请刷新页面或重新登录';
          break;
        }
        
        // 等待一秒后重试
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }

    try {
      await this.loadAllData();
    } catch (error) {
      console.error('加载用户数据失败:', error);
      this.error = '加载数据失败，请刷新页面重试';
    }

  },
  methods: {
    async loadAllData() {
      // 加载学习记录
      await this.loadStudyRecordsBasedOnIdentity();
      
      // 只有当身份是教师或助教时才加载班级信息
      if (this.currentIdentity === 'Teacher' || this.currentIdentity === 'Teaching_Assistant') {
        await this.loadClassesBasedOnIdentity();
      }
    },

    // 打开账号设置模态框
    openAccountSettingsModal() {
      this.showAccountSettingsModal = true;
      this.modalStep = 1;
      this.resetFormFields();
    },

    // 关闭账号设置模态框
    closeAccountSettingsModal() {
      this.showAccountSettingsModal = false;
      this.resetFormFields();
    },

    // 重置表单字段
    resetFormFields() {
      this.currentPassword = '';
      this.newUsername = this.user && this.user.userName ? this.user.userName : '';
      this.newPassword = '';
      this.confirmPassword = '';
      this.passwordError = '';
    },

    // 跳转详情页面
    viewLearningDetails(courseId) {
      this.$router.push({
        name: 'LearningHistory',
        params: { courseId }
      });
    },

    // 切换密码可见性
    togglePasswordVisibility(inputId) {
      const input = document.getElementById(inputId);
      if (input.type === 'password') {
        input.type = 'text';
      } else {
        input.type = 'password';
      }
    },

    // 验证密码
    async verifyPassword() {
      if (this.currentPassword.trim() === '') {
        this.passwordError = '请输入当前密码';
        return;
      }

      this.isVerifying = true;
      this.passwordError = '';
      
      // 添加重试机制
      let retryCount = 0;
      const maxRetries = 2;
      
      while (retryCount <= maxRetries) {
        try {
          // 调用后端验证密码接口
          console.log(`尝试验证密码 (尝试 ${retryCount + 1}/${maxRetries + 1})`);
          
          // 使用正确的API路径 - POST /{userId}/verify-password
          const response = await axios.post(`/api/users/${this.user.userId}/verify-password`, null, {
            params: {
              password: this.currentPassword
            }
          });
          
          // 检查响应数据
          if (response.data === true || (response.data && response.data.data === true)) {
            // 验证通过，进入设置步骤
            console.log('密码验证成功');
            this.modalStep = 2;
            this.newUsername = this.user.userName;
            return; // 成功后直接返回
          } else {
            // 密码错误但请求成功
            this.passwordError = '密码错误，请重试';
            break; // 密码错误不需要重试
          }
        } catch (error) {
          retryCount++;
          console.error(`验证密码失败 (尝试 ${retryCount}/${maxRetries + 1}):`, error);
          
          // 检查是否是401错误（未授权）
          if (error.response?.status === 401 || error.response?.status === 403) {
            this.passwordError = '会话已过期，请重新登录';
            // 可以选择重定向到登录页面
            setTimeout(() => {
              localStorage.removeItem('token');
              this.$router.push('/login');
            }, 1500);
            break; // 不再重试
          }
          
          // 如果达到最大重试次数
          if (retryCount > maxRetries) {
            this.passwordError = '服务器暂时无法响应，请稍后再试';
            break;
          }
          
          // 等待一秒后重试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
      
      this.isVerifying = false;
    },

    // 保存账号设置
    async saveAccountSettings() {
      if (this.passwordMismatch) {
        alert('两次输入的密码不一致');
        return;
      }
      
      if (!this.newUsername) {
        alert('用户名不能为空');
        return;
      }
      
      // 验证新密码长度（如果有输入新密码）
      if (this.newPassword && (this.newPassword.length < 6 || this.newPassword.length > 100)) {
        alert('新密码长度必须在6-100个字符之间');
        return;
      }

      this.isSaving = true;
      
      // 添加重试机制
      let retryCount = 0;
      const maxRetries = 2;
      let updateSuccess = false;
      
      while (retryCount <= maxRetries && !updateSuccess) {
        try {
          console.log(`尝试更新用户信息 (尝试 ${retryCount + 1}/${maxRetries + 1})`);
          
          // 准备更新数据
          const updateData = {
            currentPassword: this.currentPassword,
            newPassword: this.newPassword || "", // 确保即使没有新密码也发送空字符串
            newName: this.newUsername
          };
          
          console.log('发送更新请求，数据:', { ...updateData, currentPassword: '***', newPassword: '***' });
          
          // 使用正确的API路径和参数格式
          const response = await axios.put(
              `/api/users/${this.user.userId}`,
              updateData,
              {
                headers: {
                  'Content-Type': 'application/json'
                }
              }
          );
          
          // 处理成功响应
          console.log('更新用户信息响应:', response.data);
          
          // 更新前端用户信息（仅更新已修改的字段，避免覆盖未修改的属性）
          this.user.userName = this.newUsername; // 更新用户名
          
          // 若修改了密码，提示用户重新登录
          if (this.newPassword) {
            alert('更新成功！密码已修改，请重新登录');
            // 清除登录状态并重定向到登录页面
            setTimeout(() => {
              localStorage.removeItem('token');
              this.$router.push('/login');
            }, 1500);
          } else {
            alert('更新成功！账号信息已更新');
          }
          
          // 标记更新成功
          updateSuccess = true;
          
          // 关闭模态框
          this.closeAccountSettingsModal();
          
        } catch (error) {
          retryCount++;
          console.error(`更新用户信息失败 (尝试 ${retryCount}/${maxRetries + 1}):`, error);
          
          // 检查是否是400错误（请求参数错误）
          if (error.response?.status === 400) {
            // 尝试从错误响应中获取具体的错误信息
            const errorMessage = error.response?.data?.message || '请求参数错误';
            
            // 检查是否是密码长度错误
            if (errorMessage.includes('密码长度') || errorMessage.includes('password')) {
              alert('新密码长度必须在6-100个字符之间');
            } else if (errorMessage.includes('用户名') || errorMessage.includes('name')) {
              alert('用户名格式不正确或长度超过限制');
            } else {
              alert(`保存失败: ${errorMessage}`);
            }
            break; // 参数错误不需要重试
          }
          
          // 检查是否是401错误（未授权）
          if (error.response?.status === 401 || error.response?.status === 403) {
            alert('会话已过期，请重新登录');
            // 重定向到登录页面
            setTimeout(() => {
              localStorage.removeItem('token');
              this.$router.push('/login');
            }, 1500);
            break; // 不再重试
          }
          
          // 检查是否是密码错误
          if (error.response?.data?.message?.includes('密码错误') || 
              error.response?.data?.message?.includes('password incorrect')) {
            alert('当前密码错误，请重新输入');
            // 返回到密码验证步骤
            this.modalStep = 1;
            this.currentPassword = '';
            break; // 不再重试
          }
          
          // 如果达到最大重试次数
          if (retryCount > maxRetries) {
            alert('服务器暂时无法响应，请稍后再试');
            break;
          }
          
          // 等待一秒后重试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
      
      this.isSaving = false;
    },
    // 切换身份方法
    switchIdentity(identity) {
      this.currentIdentity = identity;
      this.loadStudyRecordsBasedOnIdentity();
      // 只有当身份是教师或助教时才加载班级信息
      if (identity === 'Teacher' || identity === 'Teaching_Assistant') {
        this.loadClassesBasedOnIdentity();
      }
    },
    // 获取学习的课程
    async loadStudyRecordsBasedOnIdentity() {
      try {
        this.isLoading = true;
        this.error = null;
        // API调用
        const coursesResponse = await axios.get(`/api/courses/users/${this.user.userId}/role/${this.currentIdentity}`);
        const courses = coursesResponse.data.data;
        // console.log(courses);
        const studyRecords = [];
        for (const course of courses) {
          // 获取课程进度
          const progressResponse = await axios.get(`/api/progress/course/${course.courseId}/student/${this.user.userId}`);
          const progress = progressResponse.data;

          studyRecords.push({
            id: course.courseId,
            thumbnail: course.image || 'https://picsum.photos/100/100',
            title: course.courseName,
            time: new Date().toLocaleString(),
            desc: course.teachingGoal || '暂无课程教学目标',
            progress: progress || 0 // 确保非空，默认0%
          });
        }

        this.studyRecords = studyRecords;
      } catch (error) {
        console.error('加载学习记录失败:', error);
        this.error = '加载学习记录失败，请稍后重试';
      } finally {
        this.isLoading = false;
      }
    },

    // 根据老师和助教身份加载班级信息
    async loadClassesBasedOnIdentity() {
      try {
        this.isLoading = true;
        this.error = null;
        
        // 增强用户信息检查，处理Proxy对象情况
        if (!this.user) {
          console.error('用户对象不存在，无法加载班级信息');
          this.classes = [];
          return;
        }
        
        // 检查用户对象是否为Proxy对象，并尝试获取实际数据
        let userId;
        if (this.user.userId) {
          userId = this.user.userId;
        } else if (this.user.data && this.user.data.userId) {
          // 如果是Proxy对象包含data属性，尝试从data中获取userId
          userId = this.user.data.userId;
          console.log('从Proxy对象的data属性中获取userId:', userId);
        } else if (this.user.target && this.user.target.data && this.user.target.data.userId) {
          // 尝试从Proxy的target属性获取userId
          userId = this.user.target.data.userId;
          console.log('从Proxy对象的target.data属性中获取userId:', userId);
        } else {
          console.error('无法从用户对象中获取有效的userId');
          console.log('用户对象结构:', JSON.stringify(this.user, (key, value) => {
            if (key === 'handler' || key === '_isReadonly' || key === '_isShallow') return '[Function]';
            return value;
          }, 2));
          this.classes = [];
          return;
        }
        
        // API调用获取班级信息，添加重试机制
        let response;
        let retryCount = 0;
        const maxRetries = 2;
        
        console.log(`尝试使用userId: ${userId} 获取班级信息`);
        
        while (retryCount <= maxRetries) {
          try {
            response = await axios.get(`/api/classes/teacher/${userId}`);
            break; // 成功获取数据，跳出循环
          } catch (retryError) {
            retryCount++;
            if (retryCount > maxRetries) {
              throw retryError; // 重试次数用完，抛出错误
            }
            console.log(`获取班级信息失败，正在进行第${retryCount}次重试...`);
            await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
          }
        }
        
        // 处理班级数据为空的情况
        if (!response || !response.data ||
            (Array.isArray(response.data) && response.data.length === 0) ||
            (typeof response.data === 'object' && Object.keys(response.data).length === 0)) {
          console.log('班级数据为空');
          this.classes = []; // 直接设置为空数组
          return; // 提前返回，无需后续处理
        }

        if (Array.isArray(response.data)) {
          this.classes = response.data;
        } else {
          this.classes = [response.data];
        }

        // 获取完成率
        const completionRatePromises = this.classes.map(async (classItem) => {
          try {
            const completionResponse = await axios.get(
                `/api/progress/class/${classItem.classesId}/completion-rate`
            );
            return {
              classesId: classItem.classesId,
              completionRate: completionResponse.data.completionRate
            };
          } catch (error) {
            console.error('获取班级完成率失败:', error);
            return {
              classesId: classItem.classesId,
              completionRate: 0 // 出错时默认0
            };
          }
        });

        const completionRates = await Promise.all(completionRatePromises);

        this.classes = await Promise.all(
            this.classes.map(async (classItem) => {
              const foundRate = completionRates.find(rate => rate.classesId === classItem.classesId);
              const exercises = await this.fetchRealExercises(classItem.classesId); // 调用真实接口

              return {
                ...classItem,
                completionRate: foundRate ? foundRate.completionRate : 0,
                exercises: exercises // 使用真实数据
              };
            })
        );


      } catch (error) {
        console.error('加载班级信息失败:', error);
        this.error = '加载班级信息失败，请稍后重试';
      } finally {
        this.isLoading = false;
      }
    },

    // 切换练习列表展开状态
    toggleExerciseList(classId) {
      if (this.expandedClassId === classId) {
        this.expandedClassId = null;
      } else {
        this.expandedClassId = classId;
      }
    },

    async fetchRealExercises(classId) {
      try {
        // 检查参数有效性
        if (!classId) {
          console.error('班级ID无效，无法获取练习数据');
          return [];
        }
        
        // 1. 获取班级下的练习列表，添加重试机制
        let exercisesResponse;
        let retryCount = 0;
        const maxRetries = 2;
        
        while (retryCount <= maxRetries) {
          try {
            exercisesResponse = await axios.get(`/api/exercises/class/${classId}`);
            break; // 成功获取数据，跳出循环
          } catch (retryError) {
            retryCount++;
            if (retryCount > maxRetries) {
              throw retryError; // 重试次数用完，抛出错误
            }
            console.log(`获取班级练习列表失败，正在进行第${retryCount}次重试...`);
            await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
          }
        }
        
        // 检查响应数据
        if (!exercisesResponse || !exercisesResponse.data) {
          console.error('获取练习列表返回数据为空');
          return [];
        }
        
        const exercises = exercisesResponse.data;
        
        // 如果没有练习，直接返回空数组
        if (!exercises || exercises.length === 0) {
          return [];
        }

        // 2. 批量获取每个练习的进度
        const progressPromises = exercises.map(async (exercise) => {
          if (!exercise || !exercise.exerciseId) {
            console.error('练习数据无效:', exercise);
            return { exerciseId: 'unknown', completionRate: 0 };
          }
          
          try {
            const progressResponse = await axios.get(
                `/api/statistics/exercise-completion-rate/${exercise.exerciseId}`
            );
            return {
              exerciseId: exercise.exerciseId,
              completionRate: progressResponse.data?.completionRate || 0
            };
          } catch (error) {
            console.error(`获取练习${exercise.exerciseId}进度失败:`, error);
            return { exerciseId: exercise.exerciseId, completionRate: 0 };
          }
        });

        const exerciseProgress = await Promise.all(progressPromises);

        // 3. 合并练习数据和进度，并格式化日期
        return exercises.map(exercise => {
          const progress = exerciseProgress.find(p => p.exerciseId === exercise.exerciseId);
          return {
            ...exercise,
            exerciseStartTime: this.formatDate(exercise.exerciseStartTime),
            exerciseDeadline: this.formatDate(exercise.exerciseDeadline),
            completionRate: progress ? progress.completionRate : 0
          };
        });
      } catch (error) {
        console.error('获取练习数据失败:', error);
        return []; // 出错时返回空数组
      }
    },

    // 生成模拟练习数据
    generateMockExercises() {
      const exerciseNames = ['Java基础练习', '数据库设计实践', 'Web开发项目', '算法练习', '数据结构作业', '面向对象设计'];
      const dateFormatter = new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });

      // 随机生成3-6个练习
      const count = Math.floor(Math.random() * 4) + 3;
      const exercises = [];

      const today = new Date();

      for (let i = 0; i < count; i++) {
        const startDate = new Date();
        startDate.setDate(today.getDate() - Math.floor(Math.random() * 7) - 3);

        const endDate = new Date(startDate);
        endDate.setDate(startDate.getDate() + Math.floor(Math.random() * 7) + 3);

        exercises.push({
          exerciseId: `E${i + 1}`,
          exerciseName: exerciseNames[Math.floor(Math.random() * exerciseNames.length)],
          exerciseStartTime: startDate,
          exerciseDeadline: endDate,
          completionRate: Math.floor(Math.random() * 101) // 0-100%随机完成率
        });
      }
      return exercises;
    },

    // 格式化日期
    formatDate(date) {
      if (!(date instanceof Date)) {
        date = new Date(date);
      }

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
  }
}

</script>



<style scoped>
/* ================ 个人信息卡片样式 ================ */
.profile-section {
  background: #f0f7ff;
  padding: 2rem 0;
}

.profile-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-main {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2rem;
}

.profile-info {
  display: flex;
  gap: 1.5rem;
  align-items: center;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.username {
  margin: 0;
  font-size: 1.75rem;
  color: #1a1a1a;
}

.account-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #666;
  font-size: 1rem;
}

.profile-actions {
  display: flex;
  gap: 1rem;
  @apply flex gap-4 mt-6;
}

.edit-btn, .settings-btn {
  padding: 0.6rem 1.2rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn:hover {
  border-color: #007bff;
  color: #007bff;
  box-shadow: 0 2px 6px rgba(0, 123, 255, 0.2);
}

.settings-btn:hover {
  border-color: #666;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* ================ 角色切换按钮样式 ================ */
.identity-switch {
  display: flex;
  gap: 1rem;
  margin: 1.5rem 0;
  justify-content: center;
}

.identity-switch button {
  padding: 0.6rem 1.2rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  font-weight: 500;
  transition: all 0.3s;
  cursor: pointer;
}

.identity-switch button.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.identity-switch button:hover {
  border-color: #007bff;
  color: #007bff;
}

/* ================ 卡片容器通用样式 ================ */
.card-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  margin: 2rem auto;
  max-width: 1200px;
  padding: 1.5rem 2rem;
}

.study-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.5rem;
}

.study-header h3 {
  margin: 0;
  font-size: 1.4rem;
  color: #1a1a1a;
  font-weight: 600;
}

/* ================ 班级管理区域样式（教师身份） ================ */
.class-list {
  display: grid;
  gap: 1.5rem;
}

.empty-classes {
  text-align: center;
  padding: 3rem 1rem;
  color: #6c757d;
}

.empty-classes i {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #a0aec0;
}

.empty-classes p {
  font-size: 1.1rem;
  margin-top: 0.5rem;
}

.study-item {
  display: flex;
  flex-direction: column; /* 改为列布局 */
  align-items: flex-start; /* 左对齐 */
  padding: 1.3rem;
  position: relative; /* 为指示器提供定位上下文 */
  gap: 1.2rem;
  border-radius: 10px;
  transition: all 0.25s ease;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  border: 1px solid transparent;
}

.study-item:hover {
  background: #f8f9fa;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.study-item.active {
  border-color: #0062cc;
  background-color: #f0f7ff;
}

.thumbnail {

  flex: 0 0 85px;
  height: 85px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  width: 100%;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.8rem;
}

.title {
  margin: 0;
  font-size: 1.1rem;
  color: #1a1a1a;
  font-weight: 600;
}

.course-name {
  font-size: 0.85rem;
  color: #6c757d;
  font-weight: 400;
}

.description {
  margin: 0 0 0.5rem;
  font-size: 0.92rem;
  color: #495057;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.progress-wrapper {
  display: flex;
  flex-direction: column;
  gap: 0.6rem;
  margin-top: 0.3rem;
}

.progress-label {
  font-size: 0.9rem;
  color: #4a5568;
  font-weight: 600;
  margin: 0;
}

.progress-percentage {
  font-size: 0.9rem;
  color: #4e73df;
  font-weight: 700;
  margin: 0;
}

/* ================ 学生列表样式 ================ */
.student-list {
  margin-top: 15px;
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  border: 1px solid #eee;
  padding: 10px;
  transition: all 0.3s ease;
}

.student-table {
  table-layout: fixed; /* 关键修复：固定表格布局 */
  width: 100%;
  border-collapse: collapse;
  font-size: 0.95rem;
}

.student-table thead {
  background-color: #f8f9fa;
}

.student-table th {
  font-weight: 600;
  color: #495057;
  text-align: left;
  padding: 12px 15px;
  border-bottom: 2px solid #dee2e6;
}

.student-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  vertical-align: middle;
  word-wrap: break-word; /* 允许长单词换行 */
}

/* 设置各列最佳宽度比例 */
.student-table th:nth-child(1),
.student-table td:nth-child(1) {
  width: 30%; /* 练习名称列 */
  text-align: center;
}

.student-table th:nth-child(2),
.student-table td:nth-child(2) {
  width: 25%; /* 开始时间列 */
}

.student-table th:nth-child(3),
.student-table td:nth-child(3) {
  width: 25%; /* 截止时间列 */
}

.student-table th:nth-child(4),
.student-table td:nth-child(4) {
  width: 20%; /* 完成进度列 */
  text-align: center; /* 进度数字居中 */
}

/* 增加时间列的文本对齐 */
.student-table th:nth-child(2),
.student-table td:nth-child(2),
.student-table th:nth-child(3),
.student-table td:nth-child(3) {
  text-align: center;
}
/* 优化表格头部样式 */
.student-table th {
  font-weight: 600;
  background-color: #f8f9fa;
  position: sticky;
  top: 0;
  z-index: 1;
}

/* 添加单元格内边距调整 */
.student-table td {
  vertical-align: middle;
  padding-top: 10px;
  padding-bottom: 10px;
}

.student-table tr:last-child td {
  border-bottom: none;
}

.student-table tr:hover {
  background-color: rgba(0, 123, 255, 0.03);
}

.student-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}

.initials-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 45px;
  height: 45px;
  border-radius: 50%;
  color: white;
  font-weight: bold;
  margin-right: 10px;
}

.toggle-indicator {
  position: absolute;
  right: 20px;
  top: 20px;
  transition: transform 0.3s ease;
}

.study-item.active .toggle-indicator {
  transform: rotate(180deg);
}

/* ================ 展示练习信息动画 ================ */

/* 学生列表动画样式 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease; /* 统一过渡时间和曲线 */
  overflow: hidden; /* 隐藏溢出内容 */
}

.slide-enter-from,
.slide-leave-to {
  max-height: 0; /* 初始高度为0 */
  opacity: 0; /* 初始透明度0 */
}

.slide-enter-to,
.slide-leave-from {
  max-height: 1000px; /* 足够大的高度容纳内容 */
  opacity: 1; /* 最终透明度1 */
}

.toggle-indicator {
  /* 原有样式 */
  transition: transform 0.3s ease; /* 与列表动画时间一致 */
}

/* ================ 响应式样式调整 ================ */
@media (max-width: 768px) {
  .profile-main {
    flex-direction: column;
    gap: 1.5rem;
  }

  .identity-switch {
    flex-wrap: wrap;
  }

  .study-item {
    flex-direction: column;
    gap: 1rem;
  }

  .thumbnail {
    position: absolute; /* 使用绝对定位不挤压其他内容 */
    width: 100%;
    height: 160px;
  }

  .meta {
    flex-direction: column;
    align-items: flex-start;
  }

  .student-table {
    font-size: 0.85rem;
  }

  .student-avatar, .initials-avatar {
    width: 35px;
    height: 35px;
  }
}

/* 新增模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-window {
  width: 460px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  animation: slideIn 0.4s ease forwards;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  align-items: flex-start;  /* 顶部对齐 */
  padding: 16px;
  position: relative;
}

.modal-header h3 {
  font-size: 22px;
  color: #202124;
  margin-bottom: 10px;
  font-weight: 500;
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: none;
  background: #f1f3f4;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  flex-shrink: 0;  /* 防止按钮被挤压 */
  margin-left: 12px; /* 添加左边距分隔 */
}

.close-btn:hover {
  background: #e4e7eb;
}

.modal-body {
  padding: 0 24px 24px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.error-message {
  color: #e74c3c;
  font-size: 0.85rem;
  margin-top: 5px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #5f6368;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 14px;
  border: 1px solid #dadce0;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.2s;
}

.form-input:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
}

.password-toggle {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 12px;
  top: 14px;
  background: none;
  border: none;
  color: #5f6368;
  cursor: pointer;
  padding: 0;
  background: transparent;
  z-index: 10;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 24px;
  border-top: 1px solid #e8eaed;
  background: #f8f9fa;
  border-radius: 0 0 12px 12px;
}

.btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-cancel {
  background: transparent;
  border: 1px solid #dadce0;
  color: #5f6368;
}

.btn-cancel:hover {
  background: #f8f9fa;
}

.btn-confirm {
  background: #007bff;
  color: white;
  border: none;
}

.btn-confirm:hover {
  background: #0069d9;
}

.btn-confirm:disabled {
  background: #b5d1f8;
  cursor: not-allowed;
}

.step-indicator {
  display: flex;
  justify-content: center;
  padding-bottom: 16px;
}

.step {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #dadce0;
  margin: 0 4px;
  transition: all 0.3s ease;
}

.step.active {
  background: #007bff;
  transform: scale(1.2);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .modal-window {
    width: 90%;
    max-width: 400px;
  }

  .profile-main {
    flex-direction: column;
    gap: 1.5rem;
  }

  .profile-actions {
    width: 100%;
    justify-content: center;
  }
}

/* 更新查看详情按钮位置和样式 */
.btn-view-detail {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem 1rem;
  background: linear-gradient(to right, #4f46e5, #7c3aed);
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  box-shadow: 0 2px 4px rgba(79, 70, 229, 0.2);
  margin-top: 1rem; /* 添加顶部边距与进度条分开 */
  align-self: flex-start; /* 左对齐 */
}

.btn-view-detail:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(79, 70, 229, 0.3);
  background: linear-gradient(to right, #6257f0, #8c4eff);
}

.btn-view-detail:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(79, 70, 229, 0.2);
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.5rem;
  transition: transform 0.2s ease;
}

.btn-view-detail:hover .icon-wrapper {
  transform: translateX(3px);
}

.btn-text {
  font-weight: 600;
  letter-spacing: 0.3px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .btn-view-detail {
    width: 100%; /* 移动端全宽 */
    justify-content: center; /* 居中显示 */
  }
}

/* 统一空状态样式 */
.empty-study-record {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 4rem 2rem;
  color: #6c757d;
}

.empty-study-record i {
  font-size: 4rem; /* 增大图标尺寸 */
  color: #e0e7ff; /* 淡蓝色图标，与系统主题一致 */
  margin-bottom: 1.5rem; /* 增加图标与文本间距 */
}

.empty-study-record p {
  font-size: 1.2rem; /* 稍大的文本字号 */
  line-height: 1.5;
  text-align: center;
}

</style>
